Skip to content

fix(pg): throw on invalid Date instead of serializing NaN string#3665

Closed
terminalchai wants to merge 1 commit intobrianc:masterfrom
terminalchai:fix/invalid-date-serialization
Closed

fix(pg): throw on invalid Date instead of serializing NaN string#3665
terminalchai wants to merge 1 commit intobrianc:masterfrom
terminalchai:fix/invalid-date-serialization

Conversation

@terminalchai
Copy link
Copy Markdown

Problem

new Date(undefined) and new Date('not a date') produce an invalid Date object whose .getTime() returns NaN. Previously prepareValue() would pass such a date straight through to dateToString() / dateToStringUTC(), which format each NaN time component with padStart(), producing the meaningless string:

0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN

Postgres cannot parse that and responds with a cryptic server-side error. The bug is especially hard to track down because the garbled string originates silently in JavaScript — the user has no indication that an invalid Date was passed in the first place.

Fixes #3318.

Fix

Add an isNaN(val.getTime()) guard in the isDate branch of prepareValue() and throw an informative error immediately:

if (isDate(val)) {
  if (isNaN(val.getTime())) {
    throw new Error('date is invalid')
  }
  // ... existing serialization
}

The error surfaces at the JavaScript call site, making the root cause immediately obvious.

Tests

Added two unit tests in packages/pg/test/unit/utils-tests.js:

  • new Date(undefined) → throws /date is invalid/
  • new Date('not a date') → throws /date is invalid/

new Date(undefined) and new Date('invalid') produce an invalid Date
object whose getTime() returns NaN.  Previously prepareValue() would
pass such a date straight through to dateToString() / dateToStringUTC()
which format each NaN component with padStart(), producing the
meaningless string '0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN' that Postgres
cannot parse.

Add an isNaN(val.getTime()) guard in the isDate branch of prepareValue()
and throw an informative error immediately, so callers discover the bug
at the JS level rather than receiving a cryptic Postgres error.

Fixes brianc#3318
@charmander charmander closed this May 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Do not serialize new Date(undefined) as "0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN"

2 participants